package dubbo.learn.registry.redis;

import dubbo.learn.common.ProviderHostAndPort;
import dubbo.learn.registry.RemoteServiceRegistry;
import lombok.Data;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
public class RedisRegistry implements RemoteServiceRegistry, BeanFactoryAware {
    /**
     * redis 注册中心的地址
     */
    private String address;

    private BeanFactory beanFactory;


    /**
     * todo:先写死
     * @param serviceName
     * @return
     */
    @Override
    public List<ProviderHostAndPort> getServiceProviderList(String serviceName) {
        RedissonClient redissonClient = beanFactory.getBean(RedissonClient.class);
        RMap<String, Long> map = redissonClient.getMap(serviceName);
        Set<String> servicesProvicerSet = map.keySet();

        if (CollectionUtils.isEmpty(servicesProvicerSet)) {
            return null;
        }
        List<ProviderHostAndPort> providerHostAndPortList = servicesProvicerSet.stream().map(providerHostAndPortItem -> {
            String[] split = providerHostAndPortItem.split(":");
            return new ProviderHostAndPort(split[0], Integer.valueOf(split[1]));
        }).collect(Collectors.toList());
        return providerHostAndPortList;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

        this.beanFactory = beanFactory;
    }
}
